<template>
  <div id="activeAuditSuccessDialog">
    <el-dialog
      :title="dialogTitle"
      :visible.sync="auditSuccessDialogData.isShow"
      width="750px"
      :destroy-on-close="true"
      class="demo-form-inline"
    >
      <div class="form-box">
        <el-form
          ref="auditSuccessForm"
          :rules="rules"
          :model="form"
          label-position="left"
          label-width="90px"
        >
          <el-form-item label="选择触达人群">
            <el-select
              v-model="form.groupType"
              placeholder="全站用户"
              @change="selectChange"
            >
              <el-option
                v-for="item in selectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
            <template v-if="form.isSms && form.groupType == 'ALL'">
              <span style="color:red;margin-left: 5px;"
                >*本次触达将产生实际费用，预计费用为：4.52万元；</span
              >
            </template>
          </el-form-item>
          <el-form-item v-if="isShowFee">
            <div class="tips">
              注意：当前选择的触达方式为“{{ touchTypeName }}”。消息{{
                touchTypeName
              }}是收费项目，{{ touchTypeName }}将会产生实际费用！
            </div>
          </el-form-item>
          <el-form-item label="起止时间" prop="createTime">
            <el-date-picker
              v-model="form.createTime"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="yyyy-MM-dd HH:mm:ss"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item v-if="peopleSelectFlag" label="搜索人群组">
            <el-input
              v-model="searchParams.searchStr"
              class="search-input"
            ></el-input>
            <el-button
              type="success"
              icon="el-icon-search"
              class="search-btn"
              @click="searchStudentGroup"
            >
              查询
            </el-button>
            <div class="bottom">
              <!-- 表格部分 -->
              <el-table
                :data="peopleTableData"
                style="width: 100%"
                class="search-table"
              >
                <el-table-column
                  prop="id"
                  label="用户群（ID）"
                  width="160"
                  align="center"
                ></el-table-column>
                <el-table-column
                  prop="name"
                  label="用户人群名称"
                  min-width="200"
                  align="center"
                ></el-table-column>
                <el-table-column label="操作" width="200" align="center">
                  <template slot-scope="scope">
                    <el-button @click="usePeople(scope.$index, scope.row)">
                      使用
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!--分页-全局组件-->
              <pageCom
                :searchParams="searchParams"
                :total="total"
                @searchList="getAllStudentGroup"
              ></pageCom>
              <!-- 已选择人群部分 -->
              <el-card>
                <div slot="header" class="clearfix">
                  <span>已选择人群</span>
                </div>
                <span
                  v-for="(item, index) in selectGroup"
                  :key="index"
                  class="selected-people"
                >
                  <span class="tag-span success people-name">{{
                    item.name
                  }}</span>
                  <span
                    class="tag-span danger delete-btn"
                    @click="deleteSelect(index, item)"
                    >删除</span
                  >
                </span>
                <template v-if="form.isSms && form.groupType !== 'ALL'">
                  <div v-if="!smsMsg" style="color:red;margin-left: 10px;">
                    加载中。。。
                  </div>
                  <div style="color:red;margin-left: 10px;">{{ smsMsg }}</div>
                </template>
              </el-card>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" @click="confirmLabel('auditSuccessForm')"
          >确 定</el-button
        >
        <el-button type="default" @click="auditSuccessDialogData.isShow = false"
          >关 闭</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getTouchPeopleAPI,
  getAllStudentGroupAPI,
  getMoneyAPI,
  editPassRequest,
  PassRequestAPI
} from '@/api/activeManagement/publish' // 接口
import qs from 'qs'
export default {
  props: ['auditSuccessDialogData'],
  data() {
    return {
      rulesNum: 0,
      dialogTitle: '活动审核通过',
      selectOptions: [
        { label: '全站用户', value: 'ALL' },
        { label: '选择用户人群', value: 'GROUP' }
      ],
      searchParams: {
        pageNum: 1,
        pageSize: 10,
        searchStr: '',
        enable: true,
        notIds: []
      },
      total: 0,
      form: {
        isSms: '',
        createTime: [],
        groupType: 'ALL',
        startTime: '', // 开始时间
        endTime: '' // 结束时间
      },
      smsMsg: '',
      peopleSelectFlag: false,
      peopleTableData: [],
      selectGroup: [],
      touchType: [],
      touchTypeName: '',
      activityId: '',
      isShowFee: false, //是否显示费用提示
      editFlag: false,
      rules: {
        createTime: [{ required: true, message: '请填写时间', trigger: 'blur' }]
      }
    }
  },
  mounted() {
    this.activityId = this.auditSuccessDialogData.activityId
    this.editFlag = this.auditSuccessDialogData.editFlag
    // 如果是编辑消息 改变标题和选中人群
    if (this.editFlag) {
      this.dialogTitle = '活动编辑'
    }
    this.getTouchPeople()
  },
  methods: {
    // 一审获取触达人群
    getTouchPeople() {
      let params = {
        activityId: this.activityId
      }
      getTouchPeopleAPI(this.activityId, params, (response) => {
        this.form = response
        this.getAllStudentGroup()
        this.selectGroup = response.selectGroup
        this.touchType = response.touchType || []
        if (response.startTime || response.endTime) {
          this.$set(this.form, 'createTime', [
            response.startTime,
            response.endTime
          ])
        }
        if (this.touchType.includes('SMS')) {
          this.touchTypeName = '短信'
        } else if (this.touchType.includes('PUSH')) {
          this.touchTypeName = '推送'
        }
        if (this.touchType.includes('SMS') || this.touchType.includes('PUSH')) {
          this.isShowFee = true
        }
        if (this.touchType.includes('SMS')) {
          if (response.selectGroup.length === 0) return
          this.getMoney(response.selectGroup)
        }
      })
    },
    // 获取所有用户人群
    getAllStudentGroup() {
      let params = this.searchParams
      let notIds = []
      this.selectGroup.map((item) => {
        notIds.push(item.id)
      })
      params.notIds = notIds.join(',')
      getAllStudentGroupAPI(params, (response) => {
        this.peopleTableData = response.rows
        this.total = response.total
      })
    },
    // 获取短信人群金额
    getMoney(obj) {
      let ids = []
      obj.forEach((item) => {
        ids.push(item.id)
      })
      let params = {
        ids: ids.join(',')
      }
      getMoneyAPI(params, (response) => {
        this.smsMsg = response.msg
      })
    },
    // 页码改变
    changePage(page) {
      this.searchParams.pageNum = page
      this.getAllStudentGroup()
    },
    // 选择人群
    usePeople(index, item) {
      if (this.rulesNum + item.rulesNum > 27) {
        this.$message.error(
          `选择的用户组超出了最大用户规则数，规则数最大为27组，当前规则数${this.rulesNum},新加入用户组规则数为${item.rulesNum}超过了27组`
        )
      } else {
        this.rulesNum = this.rulesNum + item.rulesNum
        this.peopleTableData.splice(index, 1)
        this.selectGroup.push(item)
        this.getAllStudentGroup()
        if (this.touchType.includes('SMS')) {
          this.getMoney(selectGroup)
        }
      }
    },
    // 删除选中人群
    deleteSelect(index, selectItem) {
      this.selectGroup.splice(index, 1)
      this.getAllStudentGroup()
      if (this.touchType.includes('SMS')) {
        this.getMoney(selectGroup)
      }
    },
    /* 确认提交 */
    confirmLabel(formName) {
      let _this = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          _this.confirm()
        } else {
          return false
        }
      })
    },
    // 确定按钮
    confirm() {
      if (this.touchType.includes('SMS') || this.touchType.includes('PUSH')) {
        //“短信”、“推送”为收费项目
        this.$confirm(
          `<span style="color:red;font-weight:bold;">当前选择的触达方式为“${this.touchTypeName}” 消息${this.touchTypeName}是收费项目，${this.touchTypeName}将会产生实际费用！ 确定要使用“${this.touchTypeName}”方式发布通知吗？</span>`,
          '系统提示',
          {
            dangerouslyUseHTMLString: true,
            confirmButtonText: '我确认',
            cancelButtonText: '我再想想',
            type: 'warning'
          }
        )
          .then(() => {
            this.passRequest()
          })
          .catch(() => {})
      } else {
        this.passRequest()
      }
    },
    // 审核通过请求
    passRequest() {
      if (
        this.selectValue === 'STUDENT_GROUP' &&
        this.selectGroup.length === 0
      ) {
        this.$message.error('请选择用户组')
        return
      }
      let id = []
      this.form.selectGroup.map((item) => {
        id.push(item.id)
      })
      let params = { ...this.form, groups: id }
      params.type = this.form.groupType
      delete params.groupType
      delete params.endDate
      delete params.startDate
      delete params.isSms
      delete params.touchType
      delete params.selectGroup
      delete params.createTime
      if (this.editFlag) {
        // 编辑
        editPassRequest(
          this.activityId,
          params,
          (response) => {
            this.$emit('refresh')
            this.auditSuccessDialogData.isShow = false
          },
          (response) => {
            this.$message({
              message: response.message,
              type: 'warning'
            })
          }
        )
      } else {
        // 审核通过
        PassRequestAPI(
          this.activityId,
          params,
          (response) => {
            this.$emit('refresh')
            this.auditSuccessDialogData.isShow = false
          },
          (response) => {
            this.$message({
              message: response.message,
              type: 'warning'
            })
          }
        )
      }
    },
    searchStudentGroup() {
      this.searchParams.pageNum = 1
      this.getAllStudentGroup()
    },
    selectChange(val) {
      if (val === 'GROUP') {
        this.getAllStudentGroup()
      }
    }
  },
  watch: {
    'form.createTime': {
      handler(newVal, oldVal) {
        // if (!newVal) return
        if (newVal && newVal.length > 1) {
          this.form.startTime = newVal[0]
          this.form.endTime = newVal[1]
        } else {
          this.form.startTime = ''
          this.form.endTime = ''
        }
      },
      deep: true
    },
    'form.groupType'(val) {
      this.peopleSelectFlag = val == 'ALL' ? false : true
    }
  }
}
</script>
<style lang="less">
#activeAuditSuccessDialog {
  .el-range__icon,
  .el-range-separator,
  .el-range__close-icon {
    line-height: 24px;
  }
  .form-box {
    th {
      line-height: 23px;
    }
    .bottom {
      margin-left: -90px;
      .el-table::before {
        height: 0;
      }
    }
    .el-card__header {
      padding: 4px 10px;
    }
    .page {
      margin-bottom: 15px;
    }
  }
  .tips {
    margin-top: -20px;
    font-size: 18px;
    color: red;
    // margin-left: 95px;
    font-weight: 600;
  }
  .search-input {
    width: 200px;
  }
  .search-btn {
    margin-left: 10px;
    width: 80px;
    height: 31px;
  }
  .search-table {
    margin-top: 10px;
    margin-bottom: 10px;
    max-height: 480px;
    overflow-y: auto;
  }
  .people-name {
    padding: 3px !important;
    border-top-right-radius: 0px !important;
    border-bottom-right-radius: 0px !important;
    cursor: pointer;
  }
  .delete-btn {
    padding: 3px !important;
    border-top-left-radius: 0px !important;
    border-bottom-left-radius: 0px !important;
    cursor: pointer;
  }
  .selected-people {
    display: inline-block;
    margin-right: 10px;
  }
}
</style>
